package com.xbongbong.paas.help.analysis.data;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.handle.analysis.ContractListAnalysisDataHandler;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.OptionFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.handle.AbstractOptionHandle;
import com.xbongbong.paas.pojo.dto.AnalysisDataDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.CoUserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.abstracts.AbstractSpecialDataAnalysisHelp;
import com.xbongbong.parent.parse.data.FormDataFastUpdateAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.customer.pojo.CustomerMainContactPojo;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.product.pojo.vo.RelativeProductExplainVO;
import com.xbongbong.pro.weblist.pojo.ListOptionPackagePojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.help.ProductListHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.service.PublicGroupSeniorService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.toolbox.help.AnalysisSaasDataListHelp;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 无子表单的列表解析
 * @author: wufeng
 * @date: 2018/12/5 9:44
 * @desrcption: 解析数据
 */
@Component
public class FormDataListNoSubFormAnalysisDataHelp extends FormDataListAnalysisDataHelp {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataListNoSubFormAnalysisDataHelp.class);

    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private CoUserService coUserService;
    @Resource
    private FormDataFastUpdateAnalysisDataHelp formDataFastUpdateAnalysisDataHelp;
    @Resource
    private AnalysisSaasDataListHelp analysisSaasDataListHelp;
    @Resource
    private ProductListHelp productListHelp;
    @Resource
    private Map<String, AbstractSpecialDataAnalysisHelp> webDataAnalysisHandleMap;
    @Resource
    private OptionFactory optionFactory;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private MarketingHelp marketingHelp;
    @Resource
    private PublicGroupSeniorService publicGroupSeniorService;
    /**
     * 解析数据
     * @param formDataListVO
     * @throws XbbException
     */
    @Override
    public void analysisDataList(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {

        try {
            Integer businessType = formDataListDTO.getBusinessType();
            List<PaasFormDataEntityExt> formDataEsList = formDataListVO.getPaasFormDataESList();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(formDataListVO.getHeadList().size());
            Set<String> userSet = new HashSet<>();
            Set<String> departmentSet = new HashSet<>();
            String labelAttr =null;
            String groupAttr =null;
            for (FieldAttrEntity item : formDataListVO.getHeadList()) {
                explainMap.put(item.getAttr(), item);
                Integer fieldType = item.getFieldType();
                String attr = item.getAttr();
                if (ExplainUtil.isUser(fieldType)) {
                    userSet.add(item.getAttr());
                }
                if (ExplainUtil.isDept(fieldType)) {
                    departmentSet.add(item.getAttr());
                }
                if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())){
                    labelAttr = item.getAttr();
                }

                if (Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    if (Objects.equals(attr, CustomerManagementEnum.PUBLIC_GROUP.getAttr())){
                        groupAttr = item.getAttr();
                    }
                } else if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
                    if (Objects.equals(attr, ClueEnum.PUBLIC_GROUP.getAttr())) {
                        groupAttr = item.getAttr();
                    }
                }
            }
            //将合同订单中应收、未收与合同金额可见权限一致
            List<FieldAttrEntity> list = ContractListAnalysisDataHandler.setAmountVisible(formDataListVO.getHeadList());
            list.forEach(item->{
                explainMap.put(item.getAttr(), item);
            });

            Boolean isUserTeam = UserTeamEnum.hasTeam(businessType);
            String corpid = formDataListDTO.getCorpid();
            List<Long> dataIdList = new ArrayList<>();
            // 表单中的用户和部门信息
            Set<String> userIdIn = new HashSet<>();
            Set<Long> departmentIdIn = new HashSet<>();

            for(PaasFormDataEntityExt item: formDataEsList) {
                dataIdList.add(item.getDataId());
                userSet.forEach(userAttr ->{
                    String userId = item.getData().getString(userAttr);
                    if ( Objects.nonNull(userId) ) {
                        userIdIn.add(userId);
                    }
                });
                userIdIn.add(item.getCreatorId());
                userIdIn.add(item.getOwnerId());
            }
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> paasCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            if (isUserTeam){
                Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(),subBusinessType);
                userTeamService.getUserIdMapSetShow(userIdIn,dataIdList,corpid,businessType,isPublic,mainUserMap,coUserMap);
            } else {
                paasCoUserMap = coUserService.coUserMapShow(userIdIn,dataIdList, corpid);
            }

            if (!userSet.isEmpty() || !departmentSet.isEmpty()) {
                for (PaasFormDataEntityExt item : formDataEsList) {
                    Long dataId = item.getDataId();
                    JSONObject data = item.getData();
                    // 设置创建人 负责人 协同人 所属部门
                    userIdIn.add(item.getCreatorId());
                    userIdIn.add(item.getOwnerId());
                    if (UserTeamEnum.hasTeam(businessType)) {
                        userIdIn.addAll(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
                        List<String> coUserIds = coUserMap.get(dataId);
                        if (Objects.nonNull(coUserIds)) {
                            if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.COMPETITOR.getCode(),businessType)) {
                                //产品团队只有负责人和负责部门，取了个巧，把负责部门放在了协同人中
                                List<Long> deptIds = new ArrayList<>();
                                coUserIds.forEach(deptId -> deptIds.add(Long.valueOf(deptId)));
                                departmentIdIn.addAll(deptIds);
                            } else {
                                userIdIn.addAll(coUserIds);
                            }
                        }
                    } else {
                        userIdIn.addAll(paasCoUserMap.getOrDefault(dataId, new ArrayList<>()));
                    }
                    if (!userSet.isEmpty()) {
                        userSet.forEach(key->{
                            FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                            if (Objects.nonNull(fieldAttrEntity)) {
                                Integer fieldType = fieldAttrEntity.getFieldType();
                                boolean isOwnerId = !isUserTeam && Objects.equals(FieldTypeEnum.OWNERID.getType(), fieldType);
                                if (Objects.equals(FieldTypeEnum.USER.getType(), fieldType)
                                        || Objects.equals(FieldTypeEnum.CREATORID.getType(), fieldType) && isOwnerId) {
                                    String userId = data.getString(key);
                                    if (StringUtil.isNotEmpty(userId)) {
                                        userIdIn.add(userId);
                                    }
                                } else if (Objects.equals(FieldTypeEnum.USER_GROUP.getType(), fieldType)) {
                                    JSONArray jsonArray = data.getJSONArray(key);
                                    if (Objects.nonNull(jsonArray)) {
                                        for (int i = 0; i < jsonArray.size(); i++) {
                                            String userId = jsonArray.getString(i);
                                            if (StringUtil.isNotEmpty(userId)) {
                                                userIdIn.add(userId);
                                            }
                                        }
                                    }
                                } else if (isUserTeam && Objects.equals(FieldTypeEnum.OWNERID.getType(), fieldType)) {
                                    userIdIn.addAll(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
                                } else if (isUserTeam && Objects.equals(FieldTypeEnum.COUSERID.getType(), fieldType)) {
                                    userIdIn.addAll(mainUserMap.getOrDefault(dataId, new ArrayList<>()));
                                }
                            }

                        });

                    }
                    if (!departmentSet.isEmpty()) {
                        departmentSet.forEach(key->{
                            FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                            if (Objects.nonNull(fieldAttrEntity)) {
                                Integer fieldType = fieldAttrEntity.getFieldType();
                                if (Objects.equals(FieldTypeEnum.DEPT.getType(), fieldType)) {
                                    if (data.get(key) instanceof Number || RegexUtil.isInteger(data.getString(key))) {
                                        Long departmentId = data.getLong(key);
                                        departmentIdIn.add(departmentId);
                                    }
                                } else if (Objects.equals(FieldTypeEnum.DEPT_GROUP.getType(), fieldType)) {
                                    JSONArray jsonArray = data.getJSONArray(key);
                                    if (Objects.nonNull(jsonArray)) {
                                        for (int i = 0; i < jsonArray.size(); i++) {
                                            if (jsonArray.get(i) instanceof Number) {
                                                Long departmentId = jsonArray.getLong(i);
                                                departmentIdIn.add(departmentId);
                                            }
                                        }
                                    }
                                } else if (Objects.equals(FieldTypeEnum.DEPARTMENTID.getType(), fieldType)) {
                                    if (Objects.nonNull(item.getDepartmentId())) {
                                        departmentIdIn.add(item.getDepartmentId());
                                    }
                                }
                            }
                        });

                    }

                }
            }

            Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (!userIdIn.isEmpty()) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.CORPID, corpid);
                param.put(ParameterConstant.COLUMNS, "user_id, name");
                param.put("userIdIn", userIdIn);
                param.put(ParameterConstant.LEAVE_MARKS,BasicConstant.ONE);
                List<UserEntity> userList = userModel.findEntitys(param);
                if(userList == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.USER_NOT_EXIST);
                }
                userList.forEach((item)->{
                    userMap.put(item.getUserId(), item);
                });
            }
            Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(!departmentIdIn.isEmpty()){
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.CORPID, corpid);
                param.remove("del");
                param.put(ParameterConstant.COLUMNS, "id, name");
                param.put("idIn", departmentIdIn);
                List<DepartmentEntity> departmentList = departmentModel.findEntitys(param);
                if (departmentList == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DEPT_NOT_EXIST);
                }
                departmentList.forEach((departmentItem) -> {
                    departmentMap.put(departmentItem.getId().toString(), departmentItem);
                });
            }
            AbstractOptionHandle abstractOptionHandle = optionFactory.getByBusinessType(businessType, formDataListDTO.getSaasMark());
            ListOptionPackagePojo listOptionPackagePojo = abstractOptionHandle.getFirstOptionData(formDataListDTO, formDataListVO);
            List<PaasFormDataEntityExt> resultList = new ArrayList<>();

            // 拼装地址 看不懂，先注释
            //analysisHead(formDataListVO);
            // 特殊的数据
            CustomerMainContactPojo customerMainContactPojo = new CustomerMainContactPojo();
            AbstractSpecialDataAnalysisHelp abstractSpecialDataAnalysisHelp = webDataAnalysisHandleMap.get(businessType);
            if (Objects.nonNull(abstractSpecialDataAnalysisHelp)) {
                customerMainContactPojo = abstractSpecialDataAnalysisHelp.getSpecialData(formDataListDTO, formDataListVO);
            }

            Map<String, String> lastConnectTimeMap = customerMainContactPojo.getLastConnectTimeMap();
            if (Objects.nonNull(customerMainContactPojo.getCustomerFieldList())) {
                formDataListVO.setHeadList(customerMainContactPojo.getCustomerFieldList());
            }
            boolean isOpportunity = Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), formDataListDTO.getBusinessType());
            boolean isCustomer = Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getBusinessType());
            boolean isClue = Objects.equals(XbbRefTypeEnum.CLUE.getCode(), formDataListDTO.getBusinessType());

            Map<String,Map<Long, List<JSONObject>>> productAttr2Map = customerMainContactPojo.getProductAttr2Map();
            boolean isContract = Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.ORDER.getCode(),businessType);

            // 产品分类
            Map<Long, String> categoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            boolean isProduct = Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode());
            Map<Long, List<UnitItemPoJo>> groupItemsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            HashSet<Long> promotionProductSet = new HashSet<>();
            if (isProduct) {
                categoryMap = productListHelp.categoryList(formDataListDTO.getCorpid());
                groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
                promotionProductSet = marketingHelp.getPromotionProduct(corpid);
            }
            Map<Long, LabelPojo> labelPojoMap = labelHelp.getLabelMap(formDataListDTO.getFormId(), formDataListDTO.getCorpid(), formDataListDTO.getAppId());
            //Map<Long, PublicGroupSeniorEntity> publicGroupMap = publicGroupSeniorService.getPublicGroupMap(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
            for (PaasFormDataEntityExt paasFormDataEsEntity: formDataEsList){
                JSONObject dataJsonObject = paasFormDataEsEntity.getData();
                if (Objects.nonNull(paasFormDataEsEntity.getOriginData())) {
                    dataJsonObject = paasFormDataEsEntity.getOriginData();
                    paasFormDataEsEntity.setOriginData(null);
                }
                dataJsonObject.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEsEntity.getAddTime());
                dataJsonObject.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEsEntity.getUpdateTime());
                dataJsonObject.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                dataJsonObject.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEsEntity.getDepartmentId());
                dataJsonObject.put(FieldTypeEnum.CREATORID.getAlias(), paasFormDataEsEntity.getCreatorId());
                dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), paasFormDataEsEntity.getOwnerId());
                // 客户最后跟进时间标识
                if (isCustomer) {
                    dataJsonObject.put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig()));
                }
                // 销售机会最后跟进时间标识
                if (isOpportunity) {
                    dataJsonObject.put(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.SALES_OPPORTUNITY_LAST_CONNECT_TIME.getConfig()));
                }
                labelHelp.dealId2Pojo4One(labelAttr,dataJsonObject, labelPojoMap);
//                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType) ) {
//                    //公海分组字段渲染
//                    publicGroupSeniorService.dealId2GroupName(groupAttr,dataJsonObject, publicGroupMap);
//                }
                // 线索最后跟进时间标识
                if (isClue) {
                    dataJsonObject.put(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig()));
                }

                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataListDTO, parseSingleRowDataDTO);
                dataJsonObject.put(FieldTypeEnum.CREATORID.getAlias(), paasFormDataEsEntity.getCreatorId());
                // 设置创建人
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                    parseSingleRowDataDTO.setCreatorId(dataJsonObject.getString(CustomerManagementEnum.CREATOR.getAttr()));
                } else {
                    parseSingleRowDataDTO.setCreatorId(paasFormDataEsEntity.getCreatorId());
                }
                if (isContract &&  productAttr2Map.containsKey(ContractEnum.PRODUCT.getAttr()) && CollectionsUtil.isNotEmpty(productAttr2Map.get(ContractEnum.PRODUCT.getAttr()).get(paasFormDataEsEntity.getDataId()))) {
                    dataJsonObject.put(ContractEnum.PRODUCT.getAttr(), productAttr2Map.get(ContractEnum.PRODUCT.getAttr()).get(paasFormDataEsEntity.getDataId()));
                }
                if (isProduct) {
                    //为了避免上线刷产品数据
                    if (Objects.isNull(dataJsonObject.get(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        dataJsonObject.put(ProductEnum.ENABLE_MULTI_UNIT.getAttr(), BasicConstant.ZERO);
                    }else if (Objects.equals(dataJsonObject.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE)){
                        dataJsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, groupItemsMap.get(dataJsonObject.getLongValue(ProductEnum.UNIT.getAttr())));
                    }
                }
                setOwnerIdAndCoUserId(businessType, dataJsonObject, parseSingleRowDataDTO, paasFormDataEsEntity, mainUserMap, coUserMap, paasCoUserMap);
                JSONObject cloneData = (JSONObject)dataJsonObject.clone();
                Long dataId = paasFormDataEsEntity.getId();
                paasFormDataEsEntity.setDataId(dataId);
                parseSingleRowDataDTO.setDataJsonObject(dataJsonObject);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setListFlag(1);
                parseSingleRowDataDTO.setDataId(dataId);
                parseSingleRowDataDTO.setFormId(formDataListDTO.getFormId());
                ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(parseSingleRowDataVO)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                JSONObject resultObject = parseSingleRowDataVO.getResult();

                parseSingleRowDataDTO.setDataJsonObject(cloneData);
                // 为了在列表上面可以更新数据，加下这个
                ParseSingleRowDataVO updateDataVo = formDataFastUpdateAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                if(Objects.isNull(updateDataVo)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                JSONObject sourceData = updateDataVo.getResult();

                sourceData.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEsEntity.getSerialNo());
                if (!sourceData.containsKey(FieldTypeEnum.DEPARTMENTID.getAlias())) {
                    sourceData.put(FieldTypeEnum.DEPARTMENTID.getAlias(), -1);
                }
                paasFormDataEsEntity.setSourceData(sourceData);
                // 产品分类的解析
                if (isProduct) {
                    Long categoryId = resultObject.getLong(ProductEnum.CATEGORY_ID.getAttr());
                    resultObject.put(ProductEnum.CATEGORY_ID.getAttr(), categoryMap.getOrDefault(categoryId, ""));
                    resultObject.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ZERO);
                    if (promotionProductSet.contains(dataId)) {
                        resultObject.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ONE);
                    }
                }
                // 主联系人电话不可见时，设置为*****
                if(Objects.equals(SaasMarkEnum.SAAS.getCode(), formDataListDTO.getSaasMark()) &&
                        Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataListDTO.getBusinessType())) {
                    abstractSpecialDataAnalysisHelp.setSpecialData(resultObject, dataId, customerMainContactPojo, formDataListVO, formDataListDTO.getLoginUser());
                }
                //评分处理
                handleWebListScoreShow(businessType,paasFormDataEsEntity,resultObject);
                paasFormDataEsEntity.setData(resultObject);
                // 移动端，客户、机会、合同、报价单 加上 ‘归’ 字标签 (注：web端tagData已经赋过值，不做处理)
                setAchived(formDataListDTO, resultObject, paasFormDataEsEntity);
                // 系统字段经历过一次权限的判断，所以这里加下重新赋值
                paasFormDataEsEntity.setSerialNo(resultObject.getString(FieldTypeEnum.SERIALNO.getAlias()));
                paasFormDataEsEntity.setCreatorId(resultObject.getString(FieldTypeEnum.CREATORID.getAlias()));
                paasFormDataEsEntity.setAddTime(resultObject.getLong(FieldTypeEnum.ADDTIME.getAlias()));
                paasFormDataEsEntity.setUpdateTime(resultObject.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
                paasFormDataEsEntity.setOwnerId(resultObject.getString(FieldTypeEnum.OWNERID.getAlias()));
                paasFormDataEsEntity.setAdvancePaymentBalance(paasFormDataEsEntity.getAdvancePaymentBalance());
                if (Objects.isNull(resultObject.get(FieldTypeEnum.DEPARTMENTID.getAlias()))) {
                    paasFormDataEsEntity.setDepartmentId(null);
                }
                if(Objects.equals(SaasMarkEnum.SAAS.getCode(), formDataListDTO.getSaasMark())) {
                    saasListHelp.setOptionValue(paasFormDataEsEntity, formDataListDTO, listOptionPackagePojo, formDataListDTO.getBusinessType(),
                            formDataListDTO.getSubBusinessType(), formDataListDTO.getListGroupId(), explainMap, new RelativeProductExplainVO());
                }
                resultList.add(paasFormDataEsEntity);
            }

            formDataListVO.setPaasFormDataESList(resultList);
//            removeAddress(formDataListVO);
        } catch (XbbException e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.analysisData表单列表解析数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }
    //处理评分
    private void handleWebListScoreShow(Integer businessType , PaasFormDataEntityExt paasFormDataEntityExt , JSONObject jsonObject){
        try {
            //处理评分(按照评分规则的展示区间来)
            if(XbbRefTypeEnum.checkScoreBusinessType(businessType)){
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                String scoreShowValue = scoreRangeModel.getScoreShowValue(businessType, paasFormDataEntityExt);
                switch (xbbRefTypeEnum){
                    case CUSTOMER_MANAGEMENT:
                        jsonObject.put(CustomerManagementEnum.SCORE.getAttr(), scoreShowValue);
                        break;
                    case CLUE:
                        scoreShowValue = scoreRangeModel.getScoreShowValue(businessType, paasFormDataEntityExt);
                        jsonObject.put(ClueEnum.SCORE.getAttr(), scoreShowValue);
                        break;
                }
            }
        }catch (Exception e){
            LOG.error("handleWebListScore 异常");
        }
    }

    /**
     * 解析单行数据（表单数据详情和编辑回显都获取了此接口）
     * @param parseSingleRowDataDTO
     * @throws XbbException
     * @return LinkResultDataVO 关联数据和关联查询相关
     */
    @Override
    public ParseSingleRowDataVO parseSingleRowData(ParseSingleRowDataDTO parseSingleRowDataDTO) throws XbbException{
        ParseSingleRowDataVO parseSingleRowDataVO = new ParseSingleRowDataVO();
        LinkResultDataVO linkResultDataVO = new LinkResultDataVO();
        Set<Object> linkDataSet = new HashSet<>();
        JSONObject dataJsonObject = parseSingleRowDataDTO.getDataJsonObject();
        JSONObject resultObject = (JSONObject) dataJsonObject.clone();
        try {
            Map<String, FieldAttrEntity> explainMap = parseSingleRowDataDTO.getExplainMap();
            Map<String, Object> linkData = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Iterator iterator = dataJsonObject.keySet().iterator();
            AnalysisDataDTO analysisDataDTO = new AnalysisDataDTO();
            BeanUtil.copyProperties(parseSingleRowDataDTO, analysisDataDTO);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(parseSingleRowDataDTO, handlerExplainDTO);
            while (iterator.hasNext()) {
                String key = Objects.toString(iterator.next());
                FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                if(fieldAttrEntity == null) {
                    continue;
                }
                if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                    continue;
                }
                // 子表单的解析
                if( Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.CONTACT_NUMBER.getType())
                        || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SINGLE_SUB_FORM.getType())
                        || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SWITCH_TEXT.getType())
                        || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())){
                    try {
                        JSONArray jsonArray = dataJsonObject.getJSONArray(key) == null ? new JSONArray() : dataJsonObject.getJSONArray(key);
                        JSONArray resultJsonArray = new JSONArray();
                        List<Map<String, Object>> subLinkDataList = new ArrayList<>();
                        Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMapByList(fieldAttrEntity.getSubForm().getItems());
                        // 判断高级规则
                        boolean invisibleOfScope = ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
                        if (invisibleOfScope && (Objects.isNull(parseSingleRowDataDTO.getIsProcess()) || !parseSingleRowDataDTO.getIsProcess())) {
                            // 子表单字段高级规则，列表隐藏数据
                            if (Objects.equals(1, parseSingleRowDataDTO.getListFlag())) {
                                resultObject.put(key, resultJsonArray);
                            }
                            continue;
                        }
                        for (int i = 0; i < jsonArray.size(); i++) {
                            if (!(jsonArray.get(i) instanceof Map)) {
                                continue;
                            }
                            JSONObject subJsonObject = jsonArray.getJSONObject(i);
                            Iterator subIterator = subJsonObject.keySet().iterator();
                            JSONObject subResult = new JSONObject();
                            Map<String, Object> subLinkData = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            while (subIterator.hasNext()) {
                                String subKey = Objects.toString(subIterator.next());
                                FieldAttrEntity subFieldAttrEntity = subExplainMap.get(subKey);
                                if (subFieldAttrEntity == null) {
                                    subResult.put(subKey, subJsonObject.get(subKey));
                                    continue;
                                }
                                analysisDataDTO.setAttr(subKey);
                                analysisDataDTO.setFieldAttrEntity(subFieldAttrEntity);
                                analysisDataDTO.setDataJsonObject(subJsonObject);
                                if (Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), fieldAttrEntity.getFieldType()) && Objects.equals(subFieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) && Objects.equals(1, subFieldAttrEntity.getIsRedundant())) {
                                    subResult.put(subKey, subJsonObject.get(subKey));
                                } else {
                                    analysisData(analysisDataDTO, subResult, subLinkData, linkDataSet);
                                }
                            }
                            subLinkDataList.add(subLinkData);
                            resultJsonArray.add(subResult);
                        }
                        linkData.put(key, subLinkDataList);
                        resultObject.put(key, resultJsonArray);
                    } catch (Exception e) {
                        LOG.warn("formDataListNoSubFormAnalysisDataHelp.parseSingleRowData表单单行数据解析-子表单的解析出错，dataId="+parseSingleRowDataDTO.getDataId()
                                + "--businessType=" + parseSingleRowDataDTO.getBusinessType()+"--key="+key, e);
                    }
                } else {
                    try {
                        analysisDataDTO.setAttr(key);
                        analysisDataDTO.setFieldAttrEntity(fieldAttrEntity);
                        analysisDataDTO.setDataJsonObject(dataJsonObject);
                        analysisDataDTO.setFormId(parseSingleRowDataDTO.getFormId());
                        analysisData(analysisDataDTO, resultObject, linkData, linkDataSet);
                    } catch (Exception e) {
                        LOG.warn("formDataListNoSubFormAnalysisDataHelp.parseSingleRowData表单单行数据解析-常规，dataId="+parseSingleRowDataDTO.getDataId()
                                + "--businessType=" + parseSingleRowDataDTO.getBusinessType()+"--key="+key, e);
                    }
                }
            }
            linkResultDataVO.setLinkDataSet(linkDataSet);
            linkResultDataVO.setLinkData(linkData);
            parseSingleRowDataVO.setResult(resultObject);
            parseSingleRowDataVO.setLinkResultDataVO(linkResultDataVO);
        }catch (Exception e) {
            LOG.error("formDataListNoSubFormAnalysisDataHelp.parseSingleRowData表单单行数据解析出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return parseSingleRowDataVO;
    }

    @Override
    public void analysisData(AnalysisDataDTO analysisDataDTO, JSONObject resultJsonObject,
                             Map<String, Object> linkData, Set<Object> linkDataSet) throws XbbException{
        FieldAttrEntity fieldAttrEntity = analysisDataDTO.getFieldAttrEntity();
        String key = analysisDataDTO.getAttr();
        JSONObject objectJsonObject = analysisDataDTO.getDataJsonObject();
        if (Objects.isNull(analysisDataDTO.getIsProcess()) || !analysisDataDTO.getIsProcess()) {
            FormDataAnalysisHelp.invisibleSetNull(fieldAttrEntity, analysisDataDTO, objectJsonObject);
        }
        if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), fieldAttrEntity.getFieldType()) && Objects.nonNull(objectJsonObject.get(key))) {
            // 系统业务单选
            String linkedText = fieldAttrEntity.getLinkedText();
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, objectJsonObject.getLong(key));
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, objectJsonObject.getString(linkedText));
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_LINK_TYPE, fieldAttrEntity.getLinkedType());
            jsonObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
            jsonArray.add(jsonObject);
            resultJsonObject.put(key, jsonArray);
        } else if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_MULTI.getType(), fieldAttrEntity.getFieldType()) && Objects.nonNull(objectJsonObject.get(key))) {
            // 系统业务多选
            String linkedText = fieldAttrEntity.getLinkedText();
            JSONArray businessIdList  = objectJsonObject.getJSONArray(fieldAttrEntity.getAttr()) == null ? new JSONArray() : objectJsonObject.getJSONArray(fieldAttrEntity.getAttr());
            JSONArray businessNameList = objectJsonObject.getJSONArray(linkedText) == null ? new JSONArray() : objectJsonObject.getJSONArray(linkedText);
            if (!businessIdList.isEmpty() && !businessNameList.isEmpty()) {
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < businessIdList.size(); i++) {
                    Long businessId = businessIdList.getLong(i);
                    String businessName = "";
                    if (CollectionsUtil.isNotEmpty(businessNameList) && i < businessNameList.size()) {
                        businessName = businessNameList.getString(i);
                    } else {
                        continue;
                    }
                    JSONObject linkObject = new JSONObject();
                    linkObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, businessId);
                    linkObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, businessName);
                    linkObject.put(StringConstant.SAAS_LINK_BUSINESS_LINK_TYPE,fieldAttrEntity.getLinkedType());
                    linkObject.put("saasMark", SaasMarkEnum.SAAS.getCode());
                    jsonArray.add(linkObject);
                }
                resultJsonObject.put(key, jsonArray);
            }
        } else if (Objects.equals(FieldTypeEnum.BIRTHDAY.getType(), fieldAttrEntity.getFieldType())) {
            String linkedText = fieldAttrEntity.getLinkedText();
            analysisSaasDataListHelp.formatBirthday4Show(objectJsonObject, key, linkedText);
            resultJsonObject.put(key, objectJsonObject.get(key));
        } else if (Objects.equals(FieldTypeEnum.SWITCH.getType(), fieldAttrEntity.getFieldType())) {
            if (Objects.equals(objectJsonObject.getString(key), BasicConstant.ZERO.toString())) {
                resultJsonObject.put(key, OperateTypeEnum.NO.getName());
            }else if (Objects.equals(objectJsonObject.getString(key), BasicConstant.ONE.toString())){
                resultJsonObject.put(key, OperateTypeEnum.YES.getName());
            }else {

            }
        } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType())) {
            // 交给pro/v1/form/data/otherDataList去解析，这里无需解析，多传而无解析的话，前端会变得卡顿
            resultJsonObject.put(key, null);
        } else {
            super.analysisData(analysisDataDTO, resultJsonObject, linkData, linkDataSet);
        }
    }



}
